import React, { Component } from 'react';
import { Tree, Col, Row, Icon, Spin, message, Input, Modal } from 'antd';
import styles from '../index.less';
import { getDepartment } from '@/services/user';

const { confirm } = Modal;
const { TreeNode, DirectoryTree } = Tree;

class LeftTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKeys: null,
      treeData: [],
      loadTree: true,
      expandedKeys: []
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  //获取分类树
  getCategoryTree = async (flag) => {
    const { applicationId } = this.props;
    const res = await getDepartment({ applicationId });
    // console.log(res);
    this.setState({ treeData: res, loadTree: false },() => {
      if(flag && res[0]){
        this.setState({ selectedKeys: res[0].id }, () => {
          this.props.treeNodeSelect(res[0]);
        });
      }
      
    });
  };

  //选择树
  onSelect = (keys, event) => {
    this.setState({ selectedKeys: keys[0], }, () => {
      this.props.treeNodeSelect(event.node.props);
    });
  };

  onExpand = (expandedKeys) => {
    this.setState({ expandedKeys });
  };

  //树render
  renderTreeNodes = data => {
    const { expandedKeys } = this.state;
    return data.map(item => {
      if (item.childrenDept.length > 0) {
        return (
          <TreeNode title={item.name} key={item.id} id={item.id} platformType={item.platformType}
            icon={expandedKeys.indexOf(item.id) === -1 ? 
              <img src={staticPath+"/sysKnowledge/unfold.png"} />
              : 
              <img src={staticPath+"/sysKnowledge/fold.png"} />
            }
          >
            {this.renderTreeNodes(item.childrenDept)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={item.name}
          key={item.id}
          id={item.id}
          icon={<img src={staticPath + "/sysKnowledge/leaf.png"} />}
          switcherIcon={<Icon type="minus-square" />}
          platformType={item.platformType}
        />
      );
    });
  };

  render() {
    const { treeData, loadTree, selectedKeys, expandedKeys } = this.state;

    return (
      <div className={styles.leftTree}>
        <Spin spinning={loadTree}>
          <DirectoryTree
            showLine={true}
            showIcon={true}
            selectedKeys={[selectedKeys]}
            defaultExpandAll
            onSelect={this.onSelect}
            onExpand={this.onExpand}
            expandedKeys={expandedKeys}
          >
            {this.renderTreeNodes(treeData)}
          </DirectoryTree>
        </Spin>
      </div>
    );
  }
}

export default LeftTree;
